/**
 * Created by duwei on 2018/12/1.
 */
/**
 * 金币场消息号
 */
// var MsgID = {}
// MsgID.FY_CODE_ROUTER_START = 1000;
// MsgID.FY_CODE_ROUTER_START + 69; //获取商品配置
// MsgID.FY_CODE_ROUTER_START + 70; //获取商品配置Ack
// MsgID.FY_CODE_ROUTER_START + 71; //获取商品信息
// MsgID.FY_CODE_ROUTER_START + 72; //获取商品信息Ack
// MsgID.FY_CODE_ROUTER_START + 73; //购买商品
// MsgID.FY_CODE_ROUTER_START + 74; //购买商品Ack
// MsgID.FY_CODE_ROUTER_START + 75; //购买商品 支付验证
// MsgID.FY_CODE_ROUTER_START + 76; //购买商品 支付验证Ack
// MsgID.FY_CODE_ROUTER_START + 77; //充值记录
// MsgID.FY_CODE_ROUTER_START + 78; //充值记录Ack
// MsgID.FY_CODE_ROUTER_START + 79; //到账通知


var CoinShopType = {
    FangKa: 1,
    Coin: 2,
    Diamond: 3,
    Gift: 4
}
var NewCoinShopWindow = Window.extend({
    _ccsFileName: res.NewCoinShopWindow_json,
    PAY_QMDPURL: 'http://pay.yayayouxi.com',
    _itemWidth: 280,
    _itemHeight: 548,
    itemList: [],
    limit_list: [],
    _onCCSLoadFinish: function () {
        View.prototype._onCCSLoadFinish.call(this);
        this._initNewCoinShopWindow();
    },
    addListener: function (code, listener) {
        network.addListener(code, listener, this);
    },

    _initClickListeners: function () {
        this._super();
        this._clickListeners = {
            'close': '_clickClose',
            'bg.btn_1': '_clickBtn',
            'bg.btn_2': '_clickBtn',
            'bg.btn_3': '_clickBtn',
            'bg.btn_4': '_clickBtn',
            'btn_zrdf': '_clickZrdfBtn',
            'btn_czjl': '_clickChongzhijiluBtn',

        };
    },
    _clickZrdfBtn: function () {
        // showAlert('就一个url 别着急 最后搞');
        // http://pay.yayayouxi.com/payServer/wxpay/app_pay/dist/index.html?area=xykwx&buyerId=197&source=5&ciType=2&signKey=1da83c5135293c2c391767bd907ad1eb&#http://
        var url='http://pay.yayayouxi.com/payServer/wxpay/app_pay/dist/index.html?'+'area='+app.area+'&buyerId='+gameData.uid+'&source=5&ciType=1'+'&signKey='+Crypto.MD5("feiyu-pay" + gameData.uid + app.area)+'#http://';

        DeviceUtil.savePasteBoard(url);
        showAlert("信息已复制，请粘贴分享");

    },
    _clickChongzhijiluBtn: function () {


        showWindow('NewCoinShopRecordWindow');


    },

    _initNetworkListeners: function () {

    },

    _getFangkaData: function (_ciType) {
        showLoading('数据请求中...');
        var self = this;
        var getCfgUrl = NewCoinShopCfg.NewCoinShopGetCfgUrl;
        var cfgdata = {
            area: app.area,
            buyerId: gameData.uid, //
            source: NewCoinShopCfg.NewCoinShopSource,
            ciType: 1,
            signKey: Crypto.MD5("feiyu-pay" + gameData.uid + app.area)
        };
        console.log(JSON.stringify(cfgdata));
        http.postFormData(getCfgUrl, cfgdata,
            function (response) {
                hideLoading();
                console.log(JSON.stringify(response));
                self._changeBtn(self.curIndex);
                if (response['data'] && response['data']['ciLIst'] && response['data']['ciLIst'].length > 0) {
                    self._addFangKaView(response['data']['ciLIst']);
                }

            }, function (response) {
                showAlert('抱歉，系统繁忙！');
            }
        );
    },

    _getJinbiData: function (_ciType) {
        var self = this;
        cc.loader.loadTxt(NewCoinShopCfg.proto, function (err, txt) {
            var protoBuf = dcodeIO.ProtoBuf;
            mProto.builder['Mall'] = protoBuf.loadProto(txt);
            mProto.initCommonModule('Mall');
            var version = -1;
            var productdata = cc.sys.localStorage.getItem("Mall1070" + gameData.uid);
            productdata = JSON.parse(productdata);
            if (productdata && productdata.cfgversion > -1) {
                version = productdata.cfgversion;
            }
            showLoading('数据请求中...');
            //获取转盘奖励
            network.send(1069,
                {userid: gameData.uid + "", areaid: NewCoinShopCfg.gameid, cfgversion: version}
            );
            network.send(1071,
                {userid: gameData.uid + "", areaid: NewCoinShopCfg.gameid}
            );
        });
        //配置回调
        network.addListener(1070, function (data) {
            hideLoading();
            cc.log('1070====' + JSON.stringify(data));
            if (data.product_list && data.product_list.length > 0) {
                cc.sys.localStorage.setItem("Mall1070" + gameData.uid, JSON.stringify(data));
                self._initJinBiShuJu(data.product_list);
            }
            else {
                var productdata = cc.sys.localStorage.getItem("Mall1070" + gameData.uid);
                productdata = JSON.parse(productdata);
                if (productdata.product_list && productdata.product_list.length > 0) {
                    self._initJinBiShuJu(productdata.product_list);
                }
            }
        });

        //数据刷新回调
        network.addListener(1072, function (data) {
            hideLoading();
            cc.log('1072====' + JSON.stringify(data));
            self.limit_list = {};
            for (var i = 0; i < data.limit_list.length; i++) {
                var ukey = data.limit_list[i]['pid'];
                var uvalue = data.limit_list[i]['remainval'];
                self.limit_list[ukey] = uvalue;
            }
            self.tableView.reloadData();

        });

        //数据刷新回调
        network.addListener(1079, function (data) {
            cc.log('1079====' + JSON.stringify(data));
        });

    },

    /**
     * 刷新数据，外部调用setData
     */
    refreshData: function (_ciType) {
        var self = this;
        self.curIndex = 1;
        if (_ciType) {
            self.curIndex = _ciType;
        }
        this._getFangkaData(_ciType);
        this._getJinbiData(_ciType);

        this._initUserInfo();

    },


    _clickClose: function () {
        var self = this;
        self.removeFromParent();
        network.send(3013, {});
        network.send(2103, {cmd: 'updateLocal', location: 0});
    },

    _initUserInfo: function () {
        var self = this;
        if (gameData.numOfCards && gameData.numOfCards[1] >= 0) {
            gameData.cardnum = gameData.numOfCards[1];
            self._nodeList['roomcard.txtCount'].setString(equalNum(gameData.cardnum) || "0");
        }
        if (gameData.numOfCards && gameData.numOfCards[0] >= 0) {
            gameData.coinnum = gameData.numOfCards[0];
            self._nodeList['roomcoin.txtCount'].setString(equalNum(gameData.coinnum) || "0");
        }
        if (gameData.numOfCards && gameData.numOfCards[2] >= 0) {
            gameData.diamondnum = gameData.numOfCards[2];
            self._nodeList['roomdiamond.txtCount'].setString(equalNum(gameData.diamondnum) || "0");
        }
    },

    _initJinBiShuJu: function (product_list) {
        var self = this;
        for (var i = 0; i < product_list.length; i++) {
            if (product_list[i]['tagtype'] == 'coin') {
                self.jinbiList.push(product_list[i]);
            }
            else if (product_list[i]['tagtype'] == 'diamond') {
                self.zuanshiList.push(product_list[i]);
            }
            else if (product_list[i]['tagtype'] == 'packet') {
                self.libaoList.push(product_list[i]);
            }
        }
        // cc.log('sssssss');
        //
        // cc.log(JSON.stringify(self.jinbiList));
        // cc.log(JSON.stringify(self.zuanshiList));
        // cc.log(JSON.stringify(self.libaoList));


        if (self.curIndex == 2) {
            this.itemList = self.jinbiList;
        }
        if (self.curIndex == 3) {
            this.itemList = self.zuanshiList;
        }
        if (self.curIndex == 4) {
            this.itemList = self.libaoList;
        }
        this._initCoinTableView();
        this._addGoldView(self._nodeList['bg.Node_2.scrollView'], self.jinbiList);
        this._addGoldView(self._nodeList['bg.Node_3.scrollView'], self.zuanshiList);


    },

    _initNewCoinShopWindow: function () {
        var self = this;
        for (var i = 1; i <= 4; i++) {
            self._nodeList['bg.btn_' + i].setTag(i);
            self._nodeList['bg.Node_' + i].setVisible(false);
        }
        self.jinbiList = [];
        self.zuanshiList = [];
        self.libaoList = [];

        cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () {
            network.send(1079,
                {userid: gameData.uid + "", areaid: NewCoinShopCfg.gameid}
            );
        });


        //配置回调
        network.addListener(1080, function (data) {
            // hideLoading();
            cc.log('1080====' + JSON.stringify(data));
            if (data.payresult.length > 0) {
                var messageStr = '您有' + data.payresult.length + '条支付成功消息，详情请点击充值记录';
                showAlert(messageStr);
                network.send(MsgCode.ReqFangKa, {});

            }

        });


    },
    _clickBtn: function (node) {
        // cc.log(node.getTag());
        this._changeBtn(node.getTag());

        // if()
    },
    _changeBtn: function (index) {
        var self = this;
        for (var i = 1; i <= 4; i++) {
            if (index == i) {
                self._nodeList['bg.btn_' + i + '.btnForce'].setVisible(true);
                self._nodeList['bg.Node_' + i].setVisible(true);
            }
            else {
                self._nodeList['bg.btn_' + i + '.btnForce'].setVisible(false);
                self._nodeList['bg.Node_' + i].setVisible(false);

            }
        }
        // self._nodeList['bg.Node_1'].setVisible(index == 1);
        // self._nodeList['bg.Node_2'].setVisible(index != 1);
        // // self._nodeList['btn_czjl'].setVisible(index == 1);
        self._nodeList['btn_zrdf'].setVisible(index == 1);

        self.curIndex = index;
        // switch (index) {
        //     case 2:
        //         self.itemList = self.jinbiList;
        //         break;
        //     case 3:
        //         self.itemList = self.zuanshiList;
        //         break;
        //     case 4:
        //         self.itemList = self.libaoList;
        //         break;
        //     default:
        //         break;
        // }
        if (self.tableView) {
            self.tableView.reloadData();
        }

    },
    /**
     * 添加房卡页面
     */
    _addFangKaView: function (ciLIst) {
        // cc.winSize.width
        var self = this;
        var fangkaScrollView = self._nodeList['bg.Node_1.scrollView']
        // cc.log('ciLIst.length=' + ciLIst.length);
        if (ciLIst.length > 8) {
            var size = cc.size(fangkaScrollView.getContentSize().width, fangkaScrollView.getContentSize().height + 310);
            // fangkaScrollView.setContentSize(size);
            fangkaScrollView.setInnerContainerSize(size);
        }
        for (var i = 0; i < ciLIst.length; i++) {
            var fangkaSp = duplicateNode(self._nodeList['fangkaSp']);
            fangkaSp.setVisible(true);
            var yindex = Math.floor(i / 4);
            var xindex = i % 4;
            fangkaSp.setPosition(cc.p((fangkaSp.getContentSize().width + 5) * xindex, fangkaScrollView.getInnerContainerSize().height - yindex * (fangkaSp.getContentSize().height)));
            fangkaScrollView.addChild(fangkaSp);
            var fangkaNum = ciLIst[i]['cnt'];
            var oriCnt = ciLIst[i]['oriCnt'];
            var price = ciLIst[i]['amount'];
            var jiazengNum = fangkaNum - oriCnt;
            var limit = ciLIst[i]['limit'];
            var endTime = ciLIst[i]['endTime'];
            var cid = ciLIst[i]['cid'];
            var payType = ciLIst[i]['payType'];

            fangkaSp.getChildByName('btn_buy').setTag(i);

            fangkaSp.getChildByName('fangka_' + self._getFangKaImageIndex(fangkaNum)).setVisible(true);
            fangkaSp.getChildByName('fangkaLb').setString(fangkaNum + '张房卡');
            fangkaSp.getChildByName('priceLb').setString('￥' + price);
            // leftLb
            if (limit != '') {
                fangkaSp.getChildByName('leftLb').setString('还可购' + limit + '次');
            }
            else {
                fangkaSp.getChildByName('leftLb').setVisible(false);
            }
            if (endTime == '') {
                fangkaSp.getChildByName('leftBg').setVisible(false);
                fangkaSp.getChildByName('leftTimeLb').setVisible(false);
            }
            else {
                // time2timestamp
                var time = time2timestamp(endTime);
                fangkaSp.getChildByName('leftTimeLb').setString(timeStr2(time)+'失效');
            }

            if (jiazengNum > 0) {
                fangkaSp.getChildByName('zengLb').setString('加赠' + jiazengNum + '张');
            }
            else {
                fangkaSp.getChildByName('zengLb').setVisible(false);
                fangkaSp.getChildByName('jiazengbg').setVisible(false);
            }

            TouchUtil.setOnclickListener(fangkaSp.getChildByName('btn_buy'), function (node) {
                var index = node.getTag();
                showWindow('NewCoinShopPayWindow', ciLIst[index].payType, ciLIst[index].cid, ciLIst[index].cnt, ciLIst[index].amount);

                // showMessageBox('是否购买', function () {
                //     self._getFangKaOrder(NewCoinShopCfg.wxPayType, cid, fangkaNum, price);
                // })
            }, {swallowTouches: false});
        }

    },


    _addGoldView: function (parentNode, ciLIst) {
        // cc.winSize.width
        var self = this;
        var fangkaScrollView = parentNode;
        // cc.log('ciLIst.length=' + ciLIst.length);
        if (ciLIst.length > 8) {
            var size = cc.size(fangkaScrollView.getContentSize().width, fangkaScrollView.getContentSize().height + 310);
            // fangkaScrollView.setContentSize(size);
            fangkaScrollView.setInnerContainerSize(size);
        }
        for (var i = 0; i < ciLIst.length; i++) {
            var fangkaSp = duplicateNode(self._nodeList['fangkaSp']);
            fangkaSp.setVisible(true);
            var yindex = Math.floor(i / 4);
            var xindex = i % 4;
            fangkaSp.setPosition(cc.p((fangkaSp.getContentSize().width + 5) * xindex, fangkaScrollView.getInnerContainerSize().height - yindex * (fangkaSp.getContentSize().height)));
            fangkaScrollView.addChild(fangkaSp);
            var nameStr = ciLIst[i]['name'];
            var oriCnt = ciLIst[i]['oriCnt'];
            var price = ciLIst[i]['consume']['now_val'];
            if (ciLIst[i]['flashsale']) {
                var endTime = ciLIst[i]['flashsale']['etime'];
                var time = time2timestamp(endTime);
                fangkaSp.getChildByName('leftTimeLb').setString(timeStr2(time)+'过期');
            }
            else {
                fangkaSp.getChildByName('leftBg').setVisible(false);
                fangkaSp.getChildByName('leftTimeLb').setVisible(false);
            }

            fangkaSp.getChildByName('btn_buy').setTag(i);

            // fangkaSp.getChildByName('fangka_' + self._getFangKaImageIndex(fangkaNum)).setVisible(true);
            fangkaSp.getChildByName('fangkaLb').setString(nameStr);
            if (ciLIst[i]['consume']['code'] == 'diamond') {
                fangkaSp.getChildByName('priceLb').setString(price);
                fangkaSp.getChildByName('priceLb').setPositionX(140);
                fangkaSp.getChildByName('zuanshiSp').setVisible(true);
            }
            else {
                price = price / 100;
                fangkaSp.getChildByName('priceLb').setString('￥' + price);
            }

            fangkaSp.getChildByName('zengLb').setVisible(false);
            fangkaSp.getChildByName('jiazengbg').setVisible(false);

            var iconSp = new cc.Sprite(self.getImageName(ciLIst[i]));
            iconSp.setPosition(cc.p(fangkaSp.getContentSize().width / 2, 160));
            fangkaSp.addChild(iconSp);

            //限购次数
            var remainval = self.limit_list[ciLIst[i].pid];
            if (remainval > -1) {
                fangkaSp.getChildByName('leftLb').setVisible(true);
                fangkaSp.getChildByName('leftLb').setString('还可购' + remainval + '次');
            }
            else {
                fangkaSp.getChildByName('leftLb').setVisible(false);
            }

            //购买订单
            network.addListener(1074, function (data) {
                cc.log('1074====' + JSON.stringify(data));
                hideLoading();
                if (data.errorCode == 0) {
                    if (data.prepayid != '') {
                        var openUrl = NewCoinShopCfg.NewCoinShopPayCoinUrl + 'area=' + app.area + '&buyerId=' + gameData.uid + '&source=' + NewCoinShopCfg.NewCoinShopCoinSource + '&ciType=' + citype + '&payType=6' + '&signKey=' + Crypto.MD5("feiyu-pay" + gameData.uid + app.area) + '&prepayid=' + data.prepayid + '&#http://';
                        cc.log('openUrlopenUrl==' + openUrl);
                        cc.sys.openURL(openUrl);

                    }
                    else {
                        showAlert('支付成功');
                        network.send(MsgCode.ReqFangKa, {});
                    }

                }
                else {
                    showAlert(data.errorMsg);
                }

            });
            TouchUtil.setOnclickListener(fangkaSp.getChildByName('btn_buy'), function (node) {
                var index = node.getTag();
                self._clickBuy(ciLIst[index].pid);

            }, {swallowTouches: false});
        }

    },
    //获取房卡图片
    _getFangKaImageIndex: function (num) {
        if (num <= 500) {
            return 1
        }
        else if (num <= 1000 && num > 500) {
            return 2
        }
        else if (num <= 2000 && num > 1000) {
            return 3
        }
        else {
            return 4
        }
    },
    _clickBuy: function (pid) {

        showLoading('获取订单中....');
        network.send(1073,
            {
                userid: gameData.uid + '',
                areaid: NewCoinShopCfg.gameid,
                pid: pid,
                appid: app.appId + '',
                gameid: 'mall',
                positionid: 0
            }
        );

        // showMessageBox('您是否购买该商品?', function () {
        //     //获取订单中
        //     showLoading('获取订单中....');
        //     network.send(1073,
        //         {
        //             userid: gameData.uid + '',
        //             areaid: NewCoinShopCfg.gameid,
        //             pid: pid,
        //             appid: app.appId + '',
        //             gameid: 'mall',
        //             positionid: 0
        //         }
        //     );
        // })


    },

    _initCoinTableView: function (shopType) {
        var self = this;
        var tableView = new cc.TableView(self, cc.size(1000, 547));
        tableView.setDirection(cc.SCROLLVIEW_DIRECTION_HORIZONTAL);
        tableView.setVerticalFillOrder(cc.TABLEVIEW_FILL_TOPDOWN);
        tableView.x = 0;
        tableView.y = 50;
        tableView.setDelegate(this);
        tableView.setBounceable(true);
        self._nodeList['bg.Node_4'].addChild(tableView);
        self.tableView = tableView;

    },
    /**
     * 列表事件
     * @private
     */
    tableCellTouched: function (_, cell) {
        cc.log(cell.getIdx());
    },
    /**
     * 初始化tableItem
     */
    tableCellAtIndex: function (table, idx) {
        var self = this;
        var cell = table.dequeueCell();
        var node = null;
        cell = new cc.TableViewCell();
        // cc.log(idx, self.itemList[idx]);
        node = addItem('NewCoinShopCellItem', cell, idx, self.libaoList[idx], self.limit_list, self.curIndex);
        node.setName("itemCell");
        return cell;
    },
    /**
     * 初始化tableItem
     */
    tableCellSizeForIndex: function () {
        return cc.size(this._itemWidth, this._itemHeight);
    },
    /**
     *
     * @return {Number}
     */
    numberOfCellsInTableView: function () {
        return this.libaoList.length;
    },

    _initNetworkListeners: function () {
        this._networkListeners = {
            ReqFangKa: '_onReqFangKa'
        };

    },
    /**
     * 请求房卡
     * @param data
     * @private
     */
    _onReqFangKa: function (data) {
        gameData.numOfCards = data['numof_cards'];
        var self = this;
        if (gameData.numOfCards && gameData.numOfCards[1] >= 0) {
            gameData.cardnum = gameData.numOfCards[1];
            self._nodeList['roomcard.txtCount'].setString(equalNum(gameData.cardnum) || "0");
        }
        if (gameData.numOfCards && gameData.numOfCards[0] >= 0) {
            gameData.coinnum = gameData.numOfCards[0];
            self._nodeList['roomcoin.txtCount'].setString(equalNum(gameData.coinnum) || "0");
        }
        if (gameData.numOfCards && gameData.numOfCards[2] >= 0) {
            gameData.diamondnum = gameData.numOfCards[2];
            self._nodeList['roomdiamond.txtCount'].setString(equalNum(gameData.diamondnum) || "0");
        }
    },

    getImageName: function (data) {
        var self = this;
        var nameStr = null;
        var imageIndex = 1;
        if (data.tagtype == 'coin') {
            if (data.content[0].orig_val <= 100000) {
                imageIndex = 1
            }
            else if (data.content[0].orig_val <= 1000000) {
                imageIndex = 2
            }
            else if (data.content[0].orig_val <= 2000000) {
                imageIndex = 3
            }
            else {
                imageIndex = 4
            }
            nameStr = 'modules/main/activity/res/NewCoinShopWindow/gold_' + imageIndex + '.png';
        }
        else if (data.tagtype == 'diamond') {
            if (data.content[0].orig_val <= 500) {
                imageIndex = 1
            }
            else if (data.content[0].orig_val <= 2000) {
                imageIndex = 2
            }
            else if (data.content[0].orig_val <= 10000) {
                imageIndex = 3
            }
            else {
                imageIndex = 4
            }
            nameStr = 'modules/main/activity/res/NewCoinShopWindow/zuanshi_' + imageIndex + '.png';
        }
        else {
            nameStr = data.url;
        }
        return nameStr;
    },


});